import json
import websockets
from rooms.room import Rooms, funs


class Wsserver:
    def __init__(self, host, port):
        self.server = websockets.serve(self.route, host, port)
        self.rooms = {}
        print("阔哥牛逼 ws://" + host + ":" + str(port))

    def delRoom(self, roomid):
        if self.rooms.get(roomid) is not None:
            del self.rooms[roomid]

    async def route(self, websocket, path):
        roomname = path[1:]
        if Rooms.get(roomname):
            print("A bug-maker joined game：" + roomname)
            await self.recv(websocket, Rooms[roomname], funs[roomname], roomname)

    async def recv(self, websocket, Room, funs, roomname):
        pid = None
        room = None
        while True:
            try:
                msg = await websocket.recv()
                data = json.loads(msg)
                command = data['command']
                if command == "join":
                    roomid = roomname + data['roomid']
                    if room is not None:
                        if roomid == room.roomid:
                            continue
                        room.leave(pid)
                    if self.rooms.get(roomid) is None:
                        self.rooms[roomid] = Room(self, roomid)
                    room = self.rooms[roomid]
                    pid = await room.join(websocket)
                    if pid is None:
                        await websocket.send(json.dumps({"command": "error", "info": "加入失败"}))
                        pid = None
                        room = None
                        continue
                else:
                    if room is None or not room.gaming:
                        continue
                    if funs.get(command) is None:
                        continue
                    await funs[command](room, pid, data)
                    if room is None or not room.gaming:
                        pid = None
                        room = None


            except Exception as e:
                print(e)
                if room:
                    await room.leave(pid)
                break
